<template>
    <div id="app">
      <div class="chat-app">
        <div class="contact-list">
          <h3>联系人列表</h3>
          <input v-model="searchQuery" placeholder="搜索联系人" @input="filterContacts">
          <ul>
            <li v-for="(contact, index) in filteredContacts" :key="index" @click="selectContact(index)"
              :class="{ active: selectedContactIndex === index }">
              <img :src="contact.avatar" alt="avatar" class="contact-avatar">
              {{ contact.name }}
            </li>
          </ul>
        </div>
        <div class="chat-container">
          <div v-if="selectedContact" class="chat-header">
            <img :src="selectedContact.avatar" alt="avatar" class="chat-header-avatar">
            <h3>与 {{ selectedContact.name }} 聊天</h3>
          </div>
          <div class="chat-messages">
            <div v-for="(message, index) in selectedContactMessages" :key="index"
              :class="{ 'message sent': message.sent, 'message received':!message.sent }">
              <img v-if="!message.sent" :src="selectedContact.avatar" alt="avatar" class="message-avatar">
              <div v-if="message.type === 'text'" class="message-content">{{ message.content }}</div>
              <img v-if="message.type === 'image'" :src="message.content" alt="sent image" class="sent-image">
              <div class="message-time">{{ message.time }}</div>
              <img v-if="message.sent" :src="userAvatar" alt="avatar" class="message-avatar">
            </div>
          </div>
          <div class="chat-input">
            <input v-model="newMessage" placeholder="输入消息..." @keyup.enter="sendMessage">
            <input type="file" @change="sendImage" accept="image/*">
            <button @click="sendMessage">发送</button>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import axios from 'axios';
import { ref, computed, onMounted } from 'vue';
import { config, userConfig } from '@/config/config';
  
  // 模拟联系人数据，包含初始聊天记录和头像
  let contacts = ref([
    {
      id:'1745118748443',
      name: '张三',
      avatar: 'https://picsum.photos/200/200?random=1',
      messages: [
        { content: '你好呀！', time: '2025-04-17 10:00', isSent: false, type: 'text' },
        { content: '今天过得咋样？', time: '2025-04-17 10:05', isSent: false, type: 'text' },
        { content: '还不错呢1', time: '2025-04-17 10:10', isSent: false, type: 'text' },
        { content: '还不错呢', time: '2025-04-17 10:10', isSent: true, type: 'text' },
        
      ]
    },
    {
      id:'',
      name: '李四',
      avatar: 'https://picsum.photos/200/200?random=2',
      messages: [
        { content: '最近忙啥呢？', time: '2025-04-17 11:00', isSent: false, type: 'text' },
        { content: '有空一起聚聚呀', time: '2025-04-17 11:10', isSent: false, type: 'text' },
        { content: '好呀，看你时间', time: '2025-04-17 11:15', isSent: true, type: 'text' }
      ]
    },
    {
      id:'',
      name: '王五',
      avatar: 'https://picsum.photos/200/200?random=3',
      messages: [
        { content: '项目进展如何啦？', time: '2025-04-17 13:00', isSent: false, type: 'text' },
        { content: '有啥问题随时说', time: '2025-04-17 13:15', isSent: false, type: 'text' },
        { content: '目前挺顺利的', time: '2025-04-17 13:20', isSent: true, type: 'text' }
      ]
    }
  ]);
  let contactss=ref('')

  const selectedContactIndex = ref(null);
  const selectedContact = ref(null);
  const selectedContactMessages = ref([]);
  const newMessage = ref('');
  const searchQuery = ref('');
  const userAvatar = 'https://picsum.photos/200/200?random=4';
  const socket = ref(null);
const messages = ref([]);
const messageId = ref(0);
let QiniuToken=ref()

onMounted(()=>{
  newWebSocket()
})
  
  const filteredContacts = computed(() => {
    if (searchQuery.value === '') {
      return contacts.value;
    }
    return contacts.value.filter(contact =>
      contact.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    );
  });
  
  const selectContact = (index) => {
    const actualIndex = contacts.value.findIndex(c => c.name === filteredContacts.value[index].name);
    selectedContactIndex.value = actualIndex;
    selectedContact.value = contacts.value[actualIndex];
    selectedContactMessages.value = selectedContact.value.messages;
  };
  
  const sendMessage = () => {
    if (newMessage.value.trim() !== '' && selectedContact.value) {
      
      const now = new Date();
      const time = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
      const fullMessage = `${selectedContact.value.sendId}:${newMessage.value}:${localStorage.getItem("userId")}`;
    socket.value.send(fullMessage);
      //socket.value.send(newMessage.value);
      
      selectedContact.value.messages.push({ content: newMessage.value, time, sent: true, type: 'text' });
      selectedContactMessages.value = selectedContact.value.messages;
      
      newMessage.value = '';
    }
  };
  
  const sendImage = (event) => {
    const file = event.target.files[0];
    if (file && selectedContact.value) {
      const reader = new FileReader();
      reader.onload = async (e) => {
        const now = new Date();
        const time = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
      const url= await handleFileChange(file)
       // 替换为你的七牛云存储空间域名
const domain = 'http://svftekle7.hn-bkt.clouddn.com';

// 使用 encodeURIComponent 进行 URL 编码
const encodedFileName = encodeURIComponent(url+"").replace("+", "%20");
// 拼接最终的 URL
const finalUrl = domain+"/"+url;
const userId=localStorage.getItem("userId")
        const fullMessage = selectedContact.value.sendId+":"+finalUrl+":"+userId;
        console.log(fullMessage)
    socket.value.send(fullMessage);
    
        selectedContact.value.messages.push({ content: e.target.result, time, sent: true, type: 'image' });
        selectedContactMessages.value = selectedContact.value.messages;
      };
      reader.readAsDataURL(file);
      event.target.value = '';
    }
  };

  const newWebSocket=()=>{
  
    let userDto={
      id:localStorage.getItem("userId"),
      username:localStorage.getItem("username"),
    }
    axios.post('api/Message/getUserChat',userDto,config).then(function (response){
      contactss.value=response.data.data
      console.log(contactss.value)
      contacts.value=contactss.value
    })
    socket.value = new WebSocket('ws://localhost:8080/chat');

socket.value.addEventListener('open', () => {
  socket.value.send("userId:"+localStorage.getItem("userId"))
  console.log('连接已建立');
});


socket.value.addEventListener('message', (event) => {
  console.log("接收到消息")
  messages.value.push({ id: messageId.value++, text: event.data });
  console.log(event.data)
});

socket.value.addEventListener('close', () => {
  console.log('连接已关闭');
});
  }

  const handleFileChange = async (file) => {
    //const file = fileInputRef.value.files[0];
    console.log("选择文件已触发")
    if (file) {
      console.log("已找到文件")
      const qiniuKey = await uploadAvatarToQiniu(file);
      if (qiniuKey) {
        console.log("开始上传")
        const domain = 'http://svftekle7.hn-bkt.clouddn.com'; // 替换为你的七牛云存储空间域名
        const avatarUrl = qiniuKey;
        //await sendAvatarUrlToBackend(avatarUrl);
        return avatarUrl
      }
    }return '空'
  };

  // 从后端获取上传凭证的函数，这里假设你有一个后端接口可以返回 token
const getUploadToken = async () => {
  try {
    let userDto={
      
    }
    const response = await axios.post('api/user/getQiniuToken',userDto,config)
    console.log(response)
    return response.data.data
    
  } catch (error) {
    console.error('获取上传凭证失败:', error);
    return null;
  }
};

// 上传头像到七牛云的函数
const uploadAvatarToQiniu = async (file) => {
  const token = await getUploadToken();
  QiniuToken.value=token;
  if (!token) {
    console.log("没有token",token)
    return;
  }

  const formData = new FormData();
  formData.append('token', token);
  formData.append('file', file);

  try {
    const response = await axios.post('https://up-z2.qiniup.com', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  
    const key=response.data.key
    console.log('上传到七牛云成功:', key);
    return key;
  } catch (error) {
    console.error('上传到七牛云失败:', error);
    return null;
  }
};

// 将图片地址发送给后端的函数
// const sendAvatarUrlToBackend = async (url) => {
//   try {
//    // User.value.avator=url
//     const response = await axios.post('api/user/changeAvater', User.value);
//     console.log('头像地址发送给后端成功:', response.data);
//     window.location.reload();
//     return response.data;
//   } catch (error) {
//     console.error('头像地址发送给后端失败:', error);
//     return null;
//   }
// };
  </script>
  
  <style scoped>
  #app {
    font-family: "Comic Sans MS", cursive, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #333;
    margin-top: 60px;
  }
  
  .chat-app {
    display: flex;
    width: 800px;
    margin: 0 auto;
    border: 2px solid #FF69B4;
    border-radius: 15px;
    overflow: hidden;
    box-shadow: 0 0 20px rgba(255, 105, 180, 0.3);
  }
  
  .contact-list {
    width: 250px;
    border-right: 2px solid #FF69B4;
    padding: 15px;
    background-color: #FFF0F5;
  }
  
  .contact-list input {
    width: 100%;
    padding: 8px;
    margin-bottom: 15px;
    border: 2px solid #FFB6C1;
    border-radius: 8px;
    font-size: 14px;
  }
  
  .contact-list ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
  }
  
  .contact-list li {
    padding: 12px;
    cursor: pointer;
    display: flex;
    align-items: center;
    border-radius: 8px;
  }
  
  .contact-list li.active {
    background-color: #FFB6C1;
  }
  
  .contact-list li:hover {
    background-color: #FFB6C1;
  }
  
  .contact-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 12px;
    border: 2px solid #FF69B4;
  }
  
  .chat-container {
    flex: 1;
  }
  
  .chat-header {
    padding: 15px;
    border-bottom: 2px solid #FF69B4;
    display: flex;
    align-items: center;
    background-color: #FFF0F5;
  }
  
  .chat-header-avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-right: 15px;
    border: 2px solid #FF69B4;
  }
  
  .chat-messages {
    height: 300px;
    overflow-y: auto;
    padding: 15px;
    border-bottom: 2px solid #FF69B4;
    background-color: #FFF8DC;
  }
  
  .message {
    margin-bottom: 15px;
    padding: 10px;
    border-radius: 10px;
    max-width: 70%;
    clear: both;
    display: flex;
    align-items: flex-start;
  }
  
  .message.sent {
    background-color: #98FB98;
    float: right;
    text-align: right;
    flex-direction: row-reverse;
  }
  
  .message.received {
    background-color: #ADD8E6;
    float: left;
    text-align: left;
  }
  
  .message-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin: 0 8px;
    border: 2px solid #FF69B4;
  }
  
  .message-content {
    margin-bottom: 5px;
  }
  
  .message-time {
    font-size: 12px;
    color: #666;
  }
  
  .sent-image {
    max-width: 100%;
    border-radius: 10px;
  }
  
  .chat-input {
    display: flex;
    padding: 15px;
  }
  
  .chat-input input {
    flex: 1;
    padding: 8px;
    border: 2px solid #FFB6C1;
    border-radius: 8px;
    margin-right: 12px;
    font-size: 14px;
  }
  
  .chat-input button {
    padding: 8px 15px;
    background-color: #FF69B4;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
  }
  
  .chat-input button:hover {
    background-color: #FF1493;
  }
  </style>    